import axios, {
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { HttpError, HttpResponse } from "@/types/http";
import { AxiosCanceler } from "../helper/axiosCancel";

const axiosCanceler = new AxiosCanceler();

const baseUrl = "/api";
// const baseUrl = '/';

const config = {
  baseURL: baseUrl,
  timeout: 10000,
};

const instance = axios.create(config);

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig<unknown>) => {
    // * 将当前请求添加到 pending 中
    axiosCanceler.addPending(config);
    return config;
  }
);

instance.interceptors.response.use(
  (
    res: AxiosResponse<HttpResponse, unknown>
  ): AxiosResponse<unknown, unknown> => {
    axiosCanceler.removePending(config);
    return res;
  },
  (err: AxiosError<HttpError>) => {
    return Promise.reject(err.response?.data);
  }
);

export default instance;
